package com.flowerplus.store.common.data.http;


import com.flowerplus.store.App;
import com.flowerplus.store.Logger;
import com.flowerplus.store.common.data.utils.ui.ResourcesUtil;
import com.flowerplus.store.common.execption.ApiException;
import com.flowerplus.store.common.execption.utils.ExceptionHandle;
import com.flowerplus.store.common.structure.mvp.BaseView;
import com.flowerplus.store.models.result.ApiBean;

import rx.Subscriber;


/**
 * Created by ems on 2017/2/27.
 * 统一处理 api 回调
 * code码不等于200 触发onError方法
 */
public abstract class ApiSubscriber<T extends ApiBean> extends Subscriber<T> {
//public abstract class ApiSubscriber<T extends ApiBean> extends Subject<T> {

    private BaseView mView;
    private ResourcesUtil mResourcesUtil;
    private boolean mProgress;

    public ApiSubscriber(BaseView view) {
        this(view, true);
    }

    public ApiSubscriber(BaseView view, boolean progress) {
        super();
        this.mView = view;
        mResourcesUtil = new ResourcesUtil(App.getApp().getApplicationContext());
        mProgress = progress;
    }
    @Override
    public void onStart() {
        if (mProgress)if(mView!=null) mView.showLoading();
    }
    @Override
    public void onCompleted() {
        if (mProgress) if(mView!=null)mView.hideLoading();
    }

    @Override
    public void onError(Throwable e) {
        if (mProgress)if(mView!=null) mView.hideLoading();
        e.printStackTrace();
        if (e instanceof ApiException) {
            error(e.getMessage());
        } else {
            String msg = ExceptionHandle.handle(e);
            Logger.d(msg);
            error(msg);
        }
    }


    @Override
    public void onNext(T t) {
        int code = Integer.parseInt(t.getCode());
        if (code == 0) {
            next(t);
        } else {
            ApiException exception = new ApiException(t.getMsg());
            onError(exception);
        }
    }

    public abstract void next(T t);


    public void error(String e) {
        if (mView!=null) {
            mView.error(e);
        }
    }
}
